//配置定时器，主要用于刷新率计算
#include "timer.h"
#include "delay_tick.h"
#include "sys.h"



// 通用定时器TIM3初始化
void timer3_init(u16 arr, u16 psc)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;
    // TIM2,3,4,5,6,7 
    // If(APB1 prescaler =1) x1 else x2
    // else x2
    // 由于APB1时钟被2分频为36MHz，所以TIM3的时钟频率为36MHz x 2 = 72MHz
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
    // 自动重装载值
    TIM_TimeBaseInitStruct.TIM_Period = arr;
    // 预分频系数
    TIM_TimeBaseInitStruct.TIM_Prescaler = psc;
    TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);

    NVIC_InitStruct.NVIC_IRQChannel = TIM3_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 2;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 3;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);

    TIM_Cmd(TIM3, ENABLE);
}


uint32_t last_frames = 0;
// TIM3中断处理函数，0.1S中断一次
void TIM3_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) {
        TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
        fps = (frames - last_frames) / 2;
        last_frames = frames;
    }
}
